import 'dart:collection';

import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:hive/hive.dart';
import 'package:zywz/dialog/dialog1.dart';
import 'package:zywz/widgets/EmptyPlaceholder.dart';
import 'package:zywz/widgets/enterprise_item.dart';
import 'package:zywz/utils/common_ui.dart';

import '../../api/api_client.dart';
import '../../bloc/auth/auth_bloc.dart';
import '../../bloc/auth/auth_event.dart';
import '../../bloc/home/home_bloc.dart';
import '../../bloc/home/home_event.dart';
import '../../bloc/home/home_state.dart';
import '../../bloc/profile/company_bloc.dart';
import '../../dialog/EnterpriseBindingDialog.dart';
import '../../models/user.dart';
import '../../models/user_company.dart';

class EnterpriseSelectionPage extends StatefulWidget {
  const EnterpriseSelectionPage({Key? key}) : super(key: key);

  @override
  _EnterpriseSelectionPageState createState() => _EnterpriseSelectionPageState();
}

class _EnterpriseSelectionPageState extends State<EnterpriseSelectionPage> {
  // 示例企业数据


  // 当前选中的企业
  String _currentCompanyId = '';

  // 处理企业选择
  void _handleEnterpriseSelected(AppCompanyDto enterprise,BuildContext context) {

    showSwitchDialog(context, onConfirm: (){
      context.read<CompanyBloc>().add(SetCompanyEvent(enterprise.id ?? ''));
      Navigator.pop(context);
    }, onCancel: (){
      Navigator.pop(context);
    });

  }
  // 处理企业选择
  void _handleEnterpriseDeleted(AppCompanyDto enterprise,BuildContext context) {

    showDeleteDialog(context, onConfirm: (){
      context.read<CompanyBloc>().add(DissCompanyEvent(enterprise.id ?? ''));
      Navigator.pop(context);
    }, onCancel: (){
      Navigator.pop(context);
    });

  }

  // 添加公司
  void _addCompany() async{
    // 这里可以添加添加公司的逻辑
    final result = await EnterpriseBindingDialog.show(context, title: '添加公司');
    if (result != null) {
      context.read<HomeBloc>().add(
        AddCompany(LinkedHashMap<String, dynamic>.from(result)),
      );
      // 处理返回的数据
      print('企业信息: $result');
    }
  }


  // userBox = Hive.box<User>('user_box')


  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((_) {
      context.read<CompanyBloc>().add(LoadCompanyEvent());
      // bloc:  bloc..add(LoadCompanyEvent()),
    });
    _currentCompanyId =   Hive.box<User>('user_box').get('currentUser')?.appCompanyDto?.id ?? '';
  }
  // 本地企业列表副本（用于即时UI更新）
  List<AppCompanyDto> _enterprises = [];




  @override
  Widget build(BuildContext context) {



    return MultiBlocListener(
      listeners: [
        BlocListener<HomeBloc, HomeState>(
          listener: (context, state) {
            if(state is HomeAddSuccess){
              var bocloc =  context.read<CompanyBloc>() ;
              bocloc.page = 0;
              bocloc.add(LoadCompanyEvent());
            }
          },
        ),
        BlocListener<CompanyBloc, CompanyState>(
          listener: (context, state) async {
            if(state is CompanyLoadState){
              EasyLoading.show(status: '加载中...');
              return ;
              // context.read<HomeBloc>().add(LoadHomeData());
            }
            EasyLoading.dismiss();
            if(state is CompanyErrorState){
              EasyLoading.showError(state.message);
            }else if(state is CompanyDeleteSuccessState){
              // 先从本地列表中移除（乐观更新）
              setState(() {
                _enterprises.removeWhere((e) => e.id == state.id);
              });
              EasyLoading.showSuccess('删除成功');
              context.read<AuthBloc>().add(AppStarted());
            }else if(state is CompanySetSuccessState) {
              // 更新本地企业列表
              var appCompany = _enterprises.firstWhere((e) => e.id == state.id, orElse: () => AppCompanyDto());
              final user = Hive.box<User>('user_box').get('currentUser');
              try {
                print('企业信息已更新:user : ${user?.appCompanyDto?.id}  ${user?.appCompanyDto?.name}');
                print('企业信息已更新:appCompany: ${appCompany?.id}  ${appCompany?.name}');
                user?.appCompanyDto = appCompany;

                print('企业信息已更新---Q:user : ${user?.appCompanyDto?.id}  ${user?.appCompanyDto?.name}');
                await Hive.box<User>('user_box').put('currentUser', user!);
                print('企业信息已更新: ${user.appCompanyDto?.name}');
                context.read<AuthBloc>().add(AppStarted());
              }catch(e){
              }
              setState(() {
                _currentCompanyId = state.id;
              });
            }
            if(state is CompanyDissState){
              // EasyLoading.showSuccess(state.message);
            }
          },
        )


      ],
      child: Scaffold(
        // 顶部导航栏
        appBar: AppBar(
          backgroundColor: const Color(0xFF41C7DD),
          title: const Text(
            '企业选择',
            style: TextStyle(
              color: Colors.white,
              fontSize: 18.0,
              fontWeight: FontWeight.bold,
            ),
          ),
          leading: IconButton(
            icon: const Icon(Icons.arrow_back, color: Colors.white),
            onPressed: () => Navigator.pop(context),
          ),
        ),

        // 主体内容
        body: Column(
          children: [
            Expanded(
              child:BlocConsumer<CompanyBloc, CompanyState>(
                buildWhen: (previous, current) =>  current is  CompanySuccessState  || current is CompanyEmptyState  ,
                builder: (context, state) {
                  if(state is CompanySuccessState){
                    _enterprises = state.companies;
                    if (_enterprises.isEmpty) {
                      return Center(child: EmptyPlaceholder(message: '暂无企业信息'));
                    }
                    return EnterpriseListView(
                          enterprises: _enterprises,
                          currentEnterprise: _currentCompanyId,
                          onEnterpriseSelected: (enterprise){
                            _handleEnterpriseSelected(enterprise,context);
                          },
                          onEnterpriseDeleted: (enterprise){
                            _handleEnterpriseDeleted(enterprise,context);
                          },
                        );
                  }
                  EasyLoading.dismiss();
                  if(state is CompanyEmptyState){
                    return Center(child: EmptyPlaceholder(message: '暂无企业信息'));
                  }
                  return Container();
                },
                listener: (context, state) {
                  if(state is CompanyLoadState){
                    EasyLoading.show(status: '加载中...');
                    return ;
                  }
                  EasyLoading.dismiss();
                  if(state is CompanyErrorState){
                    EasyLoading.showError(state.message);
                  }
                },
              ),
            ),

            // 底部添加按钮
            Container(
              padding: const EdgeInsets.all(16.0),
              color: Colors.white,
              child: SizedBox(
                width: double.infinity,
                child: ElevatedButton(
                  onPressed: _addCompany,
                  style: ElevatedButton.styleFrom(
                    backgroundColor: const Color(0xFF41C7DD),
                    shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(8.0),
                    ),
                    padding: const EdgeInsets.symmetric(vertical: 14.0),
                  ),
                  child: const Text(
                    '添加一个公司',
                    style: TextStyle(
                      color: Colors.white,
                      fontSize: 16.0,
                      fontWeight: FontWeight.bold,
                    ),
                  ),
                ),
              ),
            ),

          ],
        ),
      ),
    );
  }

  // 渐变背景构建器 - 从common_ui.dart复制，因为导入可能有问题
  Widget _buildGradientBackground({required Widget child}) {
    return Container(
      decoration: const BoxDecoration(
        gradient: LinearGradient(
          begin: Alignment.topCenter,
          end: Alignment.bottomCenter,
          colors: [Color(0xFFD6EFFF), Colors.white],
          stops: [0.0, 0.6],
        ),
      ),
      child: child,
    );
  }

  // 区块标题构建器 - 从common_ui.dart复制，因为导入可能有问题
  Widget _buildSectionHeader(String title, [String? trailing]) {
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      children: [
        Text(title, style: const TextStyle(fontSize: 18, fontWeight: FontWeight.bold)),
        if (trailing != null) Text(trailing, style: const TextStyle(color: Colors.grey)),
      ],
    );
  }
}